#include "databaselink.h"

namespace Common {

DatabaseLink::DatabaseLink(DatabaseType type, QString connectName, QObject *parent)
    : QObject(parent)
    , m_dbType(type)
    , m_bDbError(false)
    , m_bDbOpen(false)
{
    if(connectName.isEmpty())
    {
        m_databaseId = createDatabaseId();
    }
    else
    {
        m_databaseId = connectName;
    }
}

DatabaseLink::~DatabaseLink()
{
    this->closeDB();
}

bool DatabaseLink::init()
{
    QString dbDriver;
    switch (m_dbType)
    {
        case DB_MYSQL:
        {
            dbDriver = "QMYSQL";
            break;
        }
        case DB_SQLITE:
        {
            dbDriver = "QSQLITE";
            break;
        }
        case DB_ORACLE:
        {
            dbDriver = "QORACLE";
            break;
        }
        default:
            break;
    }

    // 添加MySql数据库
    m_database = QSqlDatabase::addDatabase(dbDriver, m_databaseId);
    QSqlError::ErrorType errorType = m_database.lastError().type();
    if (errorType != QSqlError::NoError)
    {
        m_bDbError = true;
        return false;
    }
    m_bDbError = false;
    return true;
}

bool DatabaseLink::open(const QString &hostName, const QString &dbName, const QString &dbUser, const QString &password, int port)
{
    if(hostName.isEmpty() || dbName.isEmpty() || dbUser.isEmpty() || password.isEmpty() || port <= 0 ) {
        return false;
    }

    m_database.setHostName(hostName);
    m_database.setDatabaseName(dbName);
    m_database.setUserName(dbUser);
    m_database.setPassword(password);
    m_database.setPort(port);

    if (!m_bDbOpen && !(m_bDbOpen = m_database.open()))
    {
        m_bDbError = true;
        return false;
    }
    return m_bDbOpen;
}

void DatabaseLink::closeDB()
{
    if (m_bDbOpen)
    {
        m_database.close();
    }
}

QString DatabaseLink::errorInfo() const
{
    if (m_database.lastError().type() != QSqlError::NoError)
    {
        return m_database.lastError().text();
    }
    return "";
}

QString DatabaseLink::createDatabaseId()
{
    QString uuid = QUuid::createUuid().toString();
    uuid.replace(QRegExp("\\W+"), "");
    return uuid;
}

}//namespace Common
